package com.zhipu.android.manager;


import com.zhipu.android.helper.CommonHelper;

import java.io.File;

/**
 * @file        AudioRecordManager.java
 * @function    录音管理器
 * @author      樊夏阳
 * @date        2015-12-5
 */
public class AudioRecordManager {

    public interface AudioRecordStateListener{
        void wellPrepared(boolean isPrepared);
    }

    private AudioRecordStateListener audioRecordStateListener;

    private WaveAudioRecorder waveAudioRecorder;
    private boolean isPrepared;
    private int maxVoiceLevel = 7;
    private File audioFile;

    private static AudioRecordManager sInstance = null;

    public static AudioRecordManager getInstance(){
        if (sInstance == null){
            synchronized (AudioRecordManager.class){
                if (sInstance == null){
                    sInstance = new AudioRecordManager();
                }
            }
        }
        return sInstance;
    }

    public void prepare(AudioRecordStateListener audioRecordStateListener){
        this.audioRecordStateListener = audioRecordStateListener;

        this.audioFile = CommonHelper.getDefaultAudioFile();

        try {
            this.isPrepared = false;

            waveAudioRecorder = WaveAudioRecorder.getInstanse(false);
            waveAudioRecorder.setOutputFile(this.audioFile.getAbsolutePath());
            waveAudioRecorder.prepare();
            waveAudioRecorder.start();

            this.isPrepared = true;
        } catch (Exception e) {

        }finally {
            if (this.audioRecordStateListener != null){      //回调
                this.audioRecordStateListener.wellPrepared(this.isPrepared);
            }
        }
    }

    public int getVoiceLevel(){
        int voiceLevel = 1;
        if (isPrepared){
            voiceLevel = maxVoiceLevel * waveAudioRecorder.getMaxAmplitude() / 32768 + 1;
        }
        return voiceLevel;
    }

    public File release(){
        if (isPrepared){
            waveAudioRecorder.stop();
            waveAudioRecorder.release();
            waveAudioRecorder = null;
            isPrepared = false;
        }
        return audioFile;
    }

    public void cancel(){
        if (isPrepared){
            release();
            if (audioFile != null){
                audioFile.delete();
            }
        }
    }
}
